package com.example.demo;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.baidu.translate.demo.TransApi;
import com.google.common.util.concurrent.RateLimiter;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class Translator {
	// 在平台申请的APP_ID 详见
	// http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
	private static final String APP_ID = "20230415001642192";
	private static final String SECURITY_KEY = "n6ZLznZLT4loILxCkIoC";
	TransApi api;
	RateLimiter openAiLimiter = RateLimiter.create(3.0 / 60.0);// 每分钟只能调用3次

	public Translator() {
		api = new TransApi(APP_ID, SECURITY_KEY);
	}

	public static void main(String[] args) {
		System.out.println(new Translator().translateByBaidu("hello world2"));
	}
	
	public String translateByOpenAI(String query) {
		openAiLimiter.acquire();
		return translateByOpenAI0(query);
	}

	private String translateByOpenAI0(String query) {
		String apiKey = "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";
        String urlStr = "https://api.openai.com/v1/chat/completions";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);
        String prompt=query;
//        prompt=JSONUtil.escape(prompt);
        JSONObject reqJson=new JSONObject();
        {
	        reqJson.set("model", "gpt-3.5-turbo-1106");
	        reqJson.set("messages", "gpt-3.5-turbo-1106");
	        JSONArray messages = new JSONArray(2);
	        reqJson.set("messages", messages);
	        
	        JSONObject msg1=new JSONObject();
	        msg1.set("role", "system");
	        msg1.set("content", "你是一位顶尖的翻译员,也是一位顶级的软件工程师,精通各种人类语言和编程语言,你的母语是简体中文. 你需要理解我发给你的软件开发相关的文章,把它翻译为简体中文给我,特别注意:'@数字@'是一种成对出现的特殊标记,你不能删除它们,且它们在译文中出现的位置必须与在原文中一致.");
	        messages.add(msg1);
	        
	        JSONObject msg2=new JSONObject();
	        msg2.set("role", "user");
	        msg2.set("content", prompt);
	        messages.add(msg2);
        }
        
        String data=reqJson.toJSONString(4);
        HttpEntity<String> request = new HttpEntity<>(data, headers);
        log.info("openai翻译原文:{}",data);
        ResponseEntity<String> response = restTemplate.postForEntity(urlStr, request, String.class);
        JSONObject jsonObject = JSONUtil.parseObj(response.getBody());
        String content = (String)jsonObject.getByPath("choices.0.message.content");
        log.info("openai翻译结果:{}",content);
        return content;
	}

	private String translateByBaidu0(String query) {
		String resJson = api.getTransResult(query, "auto", "zh");
		log.info("translate log: [{}] --> [{}]",query,resJson);
		try {
			Thread.sleep(1000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 会自动将unicode转换为中文
		String errorCode = (String) JSONUtil.getByPath(JSONUtil.parseObj(resJson), "error_code");
		if(errorCode!=null) {
			return null;
		}		
		return (String) JSONUtil.getByPath(JSONUtil.parseObj(resJson), "trans_result[0].dst");
	}
	
	private String translateByBaidu(String query) {
		String rs = translateByBaidu0(query);
		if(rs==null) {
			try {
				Thread.sleep(5000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			rs = translateByBaidu0(query);
		}
		return rs;
	}
	

}
